package com.wqtz.chechai.utils;

import android.util.Log;

import com.orhanobut.logger.Logger;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCancellationSignal;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.qiniu.android.storage.Zone;
import com.qiniu.android.utils.UrlSafeBase64;
import com.wqtz.chechai.api.Constans;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import cn.hugeterry.updatefun.UpdateFunGO;

/**
 * 项目名称： CheChai
 * 创建人 : Liberation
 * 创建时间: 2017/1/10 9:22
 */

/**
 * 七牛上传工具类
 *
 * @author JALEN  c9n9m@163.com
 * @version V1.0
 * @Title: ${FILE_NAME}
 * @Package cn.haodehaode.utils
 * @Description: ${todo}
 * @date 15/10/31 15:32
 */
public class QiNiuUtils {
	private static String AccessKey = Constans.QN_ACCESSKEY;
	//七牛后台的secret
	private static String SecretKey = Constans.QN_SECRETKEY;

	private static final String MAC_NAME = "HmacSHA1";
	private static final String ENCODING = "UTF-8";
	private List<String> upLoadfileName = new ArrayList<>();
	//此处为本地相册的一个图片
	private List<String> picPaths = new ArrayList<>();
	isUploadSuccess mIsUploadSuccess;
	UploadManager uploadManager;
	private JSONObject _json;
	//token时效
	private long _dataline;
	private String _encodedPutPolicy;
	private String _encodedSign;
	//上传秘钥
	private String _uploadToken;
	//文件路径
	private String keys;
	//仓库名
	private String bucketName;
	private Configuration config;

	public QiNiuUtils() {

	}

	public QiNiuUtils(List<String> fileLocalPath, List<String> upLoadFileName, isUploadSuccess isUploadSuccess) {
		this.picPaths.addAll(fileLocalPath);
		this.upLoadfileName.addAll(upLoadFileName);
		mIsUploadSuccess = isUploadSuccess;
		upLoadPic();
	}


	public void upLoadPic() {
		//上传
		for (int i = 0; i < picPaths.size(); i++) {
			upLoadPic(upLoadfileName.get(i), picPaths.get(i));
		}
	}


	public void upLoadPic(String upLoadKey, String path) {
		bucketName = Constans.BUCKET_AUTHFILE;

		try {
			// 构造上传策略
			_json = new JSONObject();
			_dataline = System.currentTimeMillis() / 1000 + 3600;
			_json.put("deadline", _dataline);// 有效时间为一个小时
			_json.put("scope", bucketName);
			//fix  please use up-z1.qiniu.com
			_json.put("zone", "bc");
			_json.put("overwrite", true);
			_json.put("check_exists", true);
			_json.put("up_host", "http://up-z1.qiniu.com");
			_encodedPutPolicy = UrlSafeBase64.encodeToString(_json
					.toString().getBytes());
			byte[] _sign = HmacSHA1Encrypt(_encodedPutPolicy, SecretKey);
			_encodedSign = UrlSafeBase64.encodeToString(_sign);
			_uploadToken = AccessKey + ':' + _encodedSign + ':'
					+ _encodedPutPolicy;
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("x:phone", "12345678");
			//解决华南无法上传
			config = new Configuration.Builder().zone(com.qiniu.android.common.Zone.zone1).build();
			uploadManager = new UploadManager(config);
			//以下api可以修改为图片地址 或者file  或者byte[];
			//测试
			uploadManager.put(path, upLoadKey, _uploadToken,
					new UpCompletionHandler() {
						@Override
						public void complete(String upLoadKey, ResponseInfo info,
						                     JSONObject response) {
							if(info.isOK()){
								mIsUploadSuccess.isUploadSusscess(upLoadKey, info, response);
								Log.e("qiniu", info.toString());
							}

						}
					}, new UploadOptions(map, null, false,
							new UpProgressHandler() {
								public void progress(String key, double percent) {
									mIsUploadSuccess.upLoadProgress(key, percent);
								}

							}, new UpCancellationSignal() {

						@Override
						public boolean isCancelled() {
							return false;
						}
					}));
		} catch (Exception e) {
			e.printStackTrace();

		}


	}


	/**
	 * 这个签名方法找了半天 一个个对出来的、、、、程序猿辛苦啊、、、 使用 HMAC-SHA1 签名方法对对encryptText进行签名
	 *
	 * @param encryptText 被签名的字符串
	 * @param encryptKey  密钥
	 * @return
	 * @throws Exception
	 */
	public static byte[] HmacSHA1Encrypt(String encryptText, String encryptKey)
			throws Exception {
		byte[] data = encryptKey.getBytes(ENCODING);
		// 根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
		SecretKey secretKey = new SecretKeySpec(data, MAC_NAME);
		// 生成一个指定 Mac 算法 的 Mac 对象
		Mac mac = Mac.getInstance(MAC_NAME);
		// 用给定密钥初始化 Mac 对象
		mac.init(secretKey);
		byte[] text = encryptText.getBytes(ENCODING);
		// 完成 Mac 操作
		return mac.doFinal(text);
	}

	//上传结果回调接口
	public interface isUploadSuccess {
		void isUploadSusscess(String key, ResponseInfo info,
		                      JSONObject response);

		void upLoadProgress(String key, double progress);
	}


}
